package org.javaboy.demo;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.framework.ProxyFactory;

import java.lang.reflect.Method;

public class Demo {
    public static void main(String[] args) {
        //这个是 Spring 中动态代理使用的对象
        ProxyFactory proxyFactory = new ProxyFactory();
        //设置被代理的对象
        proxyFactory.setTarget(new ICalculatorImpl());
        //这个属性设置为 true，就统一都使用 CGLIB 动态代理
        //这个属性为 false，就会根据情况（是否有接口）自动选择
//        proxyFactory.setProxyTargetClass(true);
        proxyFactory.setOptimize(true);
        //代理对象要实现的接口
        proxyFactory.addInterface(ICalculator.class);
        //通知/增强，这个其实就是要在被代理对象的方法上额外添加的方法
        proxyFactory.addAdvice(new MethodInterceptor() {
            @Override
            public Object invoke(MethodInvocation invocation) throws Throwable {
                Method method = invocation.getMethod();
                long startTime = System.currentTimeMillis();
                //这个就类似于前面的 method.invoke()
                Object proceed = invocation.proceed();
                long endTime = System.currentTimeMillis();
                System.out.println(method.getName() + " 方法执行耗时 " + (endTime - startTime) + " 毫秒");
                return proceed;
            }
        });
        ICalculator calculator = (ICalculator) proxyFactory.getProxy();
        calculator.add(3, 4);
    }
}
